'use strict';

const gulp = require('gulp');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const autoprefixer = require('gulp-autoprefixer');
const minifyCss = require('gulp-clean-css');
const minifyHtml = require('gulp-htmlmin');
const browserSync = require('browser-sync');
const babel = require('gulp-babel');
const runSequence = require('gulp-sequence');
const filter = require('gulp-filter');
const del = require('del');
const fs = require('fs-extra');
const sourcemaps = require('gulp-sourcemaps');

gulp.task('dev', function () {
    browserSync.init({
        files: ['api/**', 'common/**', 'components/**', 'data/**', 'images/**', 'styles/**', 'vendors/**', 'views/**'],
        server: {
            baseDir: './'
        },
        port: 8083,
        open: false
    });
    require('opn')('http://localhost:8083');
});

gulp.task('clean', function () {
    return del([
        'dist/*'
    ]);
});

gulp.task('copy', function () {
    if (!fs.existsSync('dist')) fs.mkdirSync('dist');
    fs.copySync('api', 'dist/api');
    fs.copySync('common', 'dist/common');
    fs.copySync('data', 'dist/data');
    fs.copySync('components', 'dist/components');
    fs.copySync('images', 'dist/images');
    fs.copySync('styles', 'dist/styles');
    fs.copySync('vendors', 'dist/vendors');
    fs.copySync('views', 'dist/views');
});

gulp.task('build-html', function () {
    return gulp.src(['views/**/*.html', './index.html'], { base: './'})
        .pipe(minifyHtml({
            removeComments: true,
            collapseWhitespace: true,
            removeScriptTypeAttributes: true,
            removeStyleLinkTypeAttributes: true,
            minifyJS: true,
            minifyCSS: true
        }))
        .pipe(gulp.dest('dist/'));
});

gulp.task('build-js', function () {
    const options = {
        mangle: true,
        compress: {
            sequences: true,
            dead_code: true,
            conditionals: true,
            booleans: true,
            unused: true,
            if_return: true,
            join_vars: true
        }
    };
    return gulp.src(['./api/**/*.js', './common/**/*.js', './components/**/*.js',
        './data/**/*.js', './views/**/*.js', './main.js'], { base: './' })
        .pipe(babel())
        .pipe(sourcemaps.init())
        .pipe(uglify(options))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('dist/'))
});

gulp.task('build-css', function () {
   return gulp.src(['./styles/**/*.css', './components/**/*.css', './views/**/*.css'], {base: './'})
       .pipe(autoprefixer({
           browsers: ['last 15 versions', 'IE >= 9'],
           cascade: true,
           remove:true
       }))
       .pipe(minifyCss({
           compatibility: 'ie8',
           advanced: false
       }))
       .pipe(gulp.dest('dist/'))
});

gulp.task('build', function (cb) {
    runSequence('clean', 'copy', 'build-html', ['build-js', 'build-css'])(cb);
});
